import router, { constantRoutes } from './router'
import { GetNewToken } from '@/api/admin'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { setToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { websock } from './websock'
import data from '@/data'
import { commonRoutes } from './const'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/checksig'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)
  console.log(to.path)
if(to.path == '/login') {
  window.location.href = "https://dp.yczrbhq.com/#/login";
} else {
  if (to.query && to.query.tt) {
    const token = to.query.tt
    if(token) {
      GetNewToken({ token })
        .then((res) => {
          store.commit('admin/SET_TOKEN', res.data.token)
          data.token = res.data.token
          setToken(res.data.token)
          next({ path: "/" });
        })
        .catch((err) => {
          console.log("失败111", err);
        });
    } else {
      window.location.href = "https://dp.yczrbhq.com/#/login";
    }
  }
}

  // determine whether the user has logged in

  setTimeout( async () => {
  const hasToken = store.getters.hasToken;

  console.log(hasToken, 'hasTokenhasToken');
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // 党建权限菜单
          const djPermission = await store.dispatch('admin/djPermission');
          // 外包权限菜单
          const permissions = await websock.getUserPermissionsWeb();
          // 菜单列表：公共菜单+党建权限菜单+外包权限菜单
          const userRoutes = commonRoutes.concat(djPermission, permissions);
          sessionStorage.setItem('userRoutes', JSON.stringify(userRoutes))

          // 遍历初始路由表,根据用户权限更改显示配置
          for (const item in constantRoutes) {
            // 遍历第一层
            let i = 0 // 用来控制主标签是否隐藏
            for (const it in constantRoutes[item].children) {
              // 遍历第二层
              if (userRoutes.includes(constantRoutes[item].children[it].path)) {
                constantRoutes[item].children[it].hidden = false
                i = i + 1 // 有一个标签显示就+1
              } else {
                constantRoutes[item].children[it].hidden = true
              }
            }
            // 如果没有激活任何页面，隐藏主标签
            if (i == 0) {
              constantRoutes[item].hidden = true
            }
          }

          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('admin/resetToken')
          Message.error(error || 'Has Error')
          // next(`/login?redirect=${to.path}&src=1`)
          next(`/login`)
          NProgress.done()
        }
      }
    }
  } else {
    console.log(to.path,"to.path")
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // next(`/login?redirect=${to.path}&src=2`)
      next(`/login`)
      NProgress.done()
    }
  }
}, 1000);
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
